<script lang="ts" setup>
  import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
  import { echarts, ECOption, graphicColors } from '@/hooks/core/useECharts';
  import { IDataShow } from '@/api/types';
  import { color } from 'echarts';
  import { isDark } from '@/hooks/core/useToggleDark';
  import { useAppSettingStore } from '@/store/module/useAppSettingStore';
  import { useMobile } from '@/hooks/core/useMobile';

  const props = withDefaults(defineProps<{ showData: IDataShow }>(), {
    //@ts-ignore
    showData: {} as IDataShow,
  });
  let chartInstance: Recordable;
  const currentPage = ref(1); // 当前显示的页数
  let pageSize = ref(5);
  const totalPage = computed(() => {
    return props.showData.disData.length % pageSize.value === 0
      ? props.showData.disData.length / pageSize.value
      : props.showData.disData.length / pageSize.value + 1;
  }); // 一共有多少页
  let timerId: NodeJS.Timer; // 定时器的标识
  const showLine_ref = ref<HTMLElement>(null!);
  const colorArr1 = [
    'rgba(11, 168, 44, 0.5)',
    'rgba(44, 110, 255, 0.5)',
    'rgba(22, 242, 217, 0.5)',
    'rgba(254, 33, 30, 0.5)',
    'rgba(250, 105, 0, 0.5)',
  ];
  // 全透明的颜色值
  const colorArr2 = [
    'rgba(11, 168, 44, 0)',
    'rgba(44, 110, 255, 0)',
    'rgba(22, 242, 217, 0)',
    'rgba(254, 33, 30, 0)',
    'rgba(250, 105, 0, 0)',
  ];
  let ranInt = Math.floor(
    Math.random() * (isDark.value ? graphicColors.length : colorArr1.length)
  ) as unknown as number;
  const initChart = () => {
    try {
      chartInstance = echarts.init(showLine_ref.value);
    } catch (e) {}
    // 对图表初始化配置的控制
    const initOption = {
      color: color,
      title: {
        // text: '▎商家销售统计',
        left: 20,
        top: 15,
        textStyle: {},
      },
      grid: {
        top: '20%',
        left: '5%',
        right: '6%',
        bottom: '5%',
        containLabel: true, // 距离是包含坐标轴上的文字
        // shadowColor: 'rgba(255, 255, 255, 1)',
        // shadowBlur: 10,
        // shadowOffsetX: 5,
        // shadowOffsetY: -5,
        // show: true,
      },
      xAxis: {
        type: 'category',
      },
      yAxis: {
        type: 'value',
        name: '单位（人次）',
        nameTextStyle: {
          fontStyle: 'oblique',
          align: 'right',
        },
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          show: true,
          type: 'cross',
        },
      },
      series: [
        {
          type: 'line',
          smooth: true,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: isDark.value ? graphicColors[ranInt][0] : colorArr1[ranInt],
              }, // %0的颜色值
              {
                offset: 1,
                color: isDark.value ? graphicColors[ranInt][1] : colorArr2[ranInt],
              }, // 100%的颜色值
            ]),
          },
          lineStyle: {
            // color: isDark.value ? graphicColors[ranInt][0] : colorArr1[ranInt],
          },
          itemStyle: {
            color: isDark.value ? graphicColors[ranInt][0] : colorArr1[ranInt],
          },
          markPoint: {
            data: [
              {
                type: 'max',
                name: 'Max',
              },
              {
                type: 'min',
                name: 'Min',
              },
            ],
            itemStyle: {
              color: isDark.value ? graphicColors[ranInt][0] : colorArr1[ranInt],
              opacity: 0.5,
            },
            label: {
              color: isDark.value ? 'white' : 'black',
            },
          },
          markLine: {
            data: [
              {
                type: 'average',
                name: 'Avg',
              },
            ],
            label: {
              show: true,
              formatter: '{b}: {c}',
              position: 'insideEndTop',
            },
            lineStyle: {
              cap: 'square',
            },
          },
        },
      ],
    };
    chartInstance.setOption(initOption);
    // 对图表对象进行鼠标事件的监听
    chartInstance.on('mouseover', () => {
      clearInterval(timerId);
    });
    chartInstance.on('mouseout', () => {
      startInterval();
    });
  };
  const screenAdapter = () => {
    const titleFontSize = (showLine_ref.value.offsetWidth / 100) * 3;
    // 和分辨率大小相关的配置项
    const adapterOption = {
      title: {
        textStyle: {
          fontSize: titleFontSize,
        },
      },
      yAxis: {
        nameTextStyle: {
          fontSize: titleFontSize * 0.5,
        },
      },
    };
    chartInstance.setOption(adapterOption);
    // 手动的调用图表对象的resize 才能产生效果
    chartInstance.resize();
  };
  const destroyed = () => {
    clearInterval(timerId);
    // 在组件销毁的时候, 需要将监听器取消掉
    window.removeEventListener('resize', screenAdapter);
  };
  const updateECharts = () => {
    if (currentPage.value === 0) {
      // eslint-disable-next-line vue/no-mutating-props
      props.showData.xAxis.reverse();
    }
    const end = currentPage.value * pageSize.value;
    const showPageData = props.showData.disData.slice(0, end);
    const showPageName = props.showData.xAxis.slice(0, end);
    const dataOption = {
      title: {
        text: '▎' + props.showData.disName,
      },
      xAxis: {
        data: showPageName,
      },
      series: [
        {
          data: showPageData,
        },
      ],
    };
    chartInstance.setOption(dataOption);
  };
  const startInterval = () => {
    if (timerId) {
      clearInterval(timerId);
    }
    timerId = setInterval(() => {
      currentPage.value++;
      if (currentPage.value > totalPage.value + 1) {
        currentPage.value = 1;
      }
      updateECharts();
    }, 3000);
  };
  const isMobile = useMobile();
  watch(isMobile, (value) => {
    chartInstance.setOption({
      yAxis: {
        nameLocation: value ? 'start' : 'end',
      },
    });
  });
  watch(isDark, (value) => {
    ranInt = Math.floor(
      Math.random() * (value ? graphicColors.length : colorArr1.length)
    ) as unknown as number;
    chartInstance.setOption({
      title: {
        textStyle: {
          color: value ? '#fff' : '#333',
        },
      },
      yAxis: {
        nameTextStyle: {
          color: isDark.value ? '#fff' : '#333',
        },
      },
      series: [
        {
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: value ? graphicColors[ranInt][0] : colorArr1[ranInt],
              }, // %0的颜色值
              {
                offset: 1,
                color: value ? graphicColors[ranInt][1] : colorArr2[ranInt],
              }, // 100%的颜色值
            ]),
          },
          itemStyle: {
            color: value ? graphicColors[ranInt][0] : colorArr1[ranInt],
          },
          markPoint: {
            itemStyle: {
              color: value ? graphicColors[ranInt][0] : colorArr1[ranInt],
              opacity: 0.5,
            },
            label: {
              color: value ? 'white' : 'black',
            },
          },
        },
      ],
    });
  });
  onMounted(() => {
    initChart();
    window.addEventListener('resize', screenAdapter);
    // 在页面加载完成的时候, 主动进行屏幕的适配
    screenAdapter();
    updateECharts();
    startInterval();
  });
  onUnmounted(() => {
    destroyed();
  });
  const appSettingStore = useAppSettingStore();
  watch(
    () => appSettingStore.configMenu.collapse,
    () => {
      setTimeout(() => {
        screenAdapter();
      }, 500);
    }
  );
</script>

<!-- 商家销量统计的横向柱状图 -->
<template>
  <div class="com-chart h-64 sm:h-96 enter-y" ref="showLine_ref"></div>
</template>

<style lang="scss">
  .com-chart {
    @media (min-width: 1920px) {
      height: 450px;
    }
  }
</style>
